package weeny.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class ArrayMap<K,V> implements Map<K,V>{
	private ArrayList<K> keys = new ArrayList<K>();
	private Map<K,V> map = new LinkedHashMap<K, V>();
	
	public int indexOfKey(Object key){
		return keys.indexOf(key);
	}
	public V put(K key, V value){
		V old = map.put(key, value);
		if (old == null) {
			keys.add(key);
		}
		return old;
	}
	public V firstValue(){
		return map.get(keys.get(0));
	}
	public V lastValue(){
		return map.get(keys.get(keys.size()-1));
	}
	public K firstKey(){
		return keys.get(0);
	}
	public K lastKey(){
		return keys.get(keys.size()-1);
	}
	public V valueAt(int index){
		return map.get(keys.get(index));
	}
	public K keyAt(int index){
		return keys.get(index);
	}

	/*
	 * Map interfaces
	 */
	public int size() {
		return map.size();
	}
	public boolean isEmpty() {
		return map.isEmpty();
	}
	public boolean containsKey(Object key) {
		return map.containsKey(key);
	}
	public boolean containsValue(Object value) {
		return map.containsValue(value);
	}
	public V remove(Object key) {
		V old = map.remove(key);
		if (old != null) {
			keys.remove(key);
		}
		return old;
	}
	public void putAll(Map<? extends K, ? extends V> m) {
		for(Iterator it = m.keySet().iterator(); it.hasNext();){
			K key = (K) it.next();
			V val = m.get(key);
			put(key, val);
		}
	}
	public void clear() {
		map.clear();
		keys.clear();
	}
	public Set<K> keySet() {
		return map.keySet();
	}
	public Collection<V> values() {
		return map.values();
	}
	public Set<java.util.Map.Entry<K, V>> entrySet() {
		return map.entrySet();
	}
	public V get(Object key) {
		return map.get(key);
	}
}
